<?php

namespace app\admin\controller;
use app\admin\model\WechatModel;
use app\admin\model\MemberModel;
use think\Db;

class Wechat extends Base
{

    /**
     * [index_cate 社会机构列表]
     * @return [type] [description]
     * @author [沈晶晶] [334554156@qq.com]
     */
    public function index(){
        $cate = new WechatModel();
        $list = $cate->getAllWechat();
        if($list){
            foreach($list as $key=>$val){
                $url = $_SERVER['SERVER_NAME'];
                $urls  = "http://".$url."/index/weixin/index/wechat_id/".$val['id'].".html";
                $list[$key]['urls'] = $urls;
            }
        }

        $this->assign('list',$list);
        return $this->fetch();
    }




    public function wechat_add()
    {
       if(request()->isAjax()){


           $count = Db::name('wechat')->where('instit_id',session('instit_id'))->count();
           if($count>0){
               return json(['code' =>11,  'msg' => '每个机构只能添加一个微信公众号']);
           }


            $wechat = new WechatModel();
            $param = input('post.');
            if(empty($param['status'])){
               $param['status'] = 0;
            }
            $param['create_time'] = time();
            $param['instit_id'] = session('instit_id');
            $flag = $wechat->insertWechat($param);
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
       }

        return $this->fetch();
    }




    public function wechat_edit()
    {
        $id = input('param.id');
        $wechat = new WechatModel();
        if(request()->isAjax()){
            $param = input('post.');
            if(empty($param['status'])){
                $param['status'] = 0;
            }
            unset($param['file']);

            $flag = $wechat->editWechat($param);
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }

        $this->assign('wechat',$wechat->getOneWechat($id));
        return $this->fetch();
    }



    public function wechat_menu(){

        $cate = new WechatModel();
        $list = $cate->getAllWechatMenu();
        foreach($list as $k=>$v){
            $lt  = $cate->getAllWechatMenu($v['id']);
            if($lt){
                $list[$k]['son'] =$lt;
            }else{
                $list[$k]['son'] ='';
            }
        }

        $this->assign('list',$list);
        return $this->fetch();
    }


    public function menu_add()
    {

        $pid = input('pid');


        if(request()->isAjax()){
            $wechat = new WechatModel();
            $param = input('post.');

            $pids = $param['pid'];
            if($pids==0){
                $mapd = array(
                    'instit_id'=>session('instit_id'),
                    'pid'=>$pids,
                );
              $count1 =   Db::name('wechat_menu')->where($mapd)->count();
                if($count1>=3){
                    return json(['code'=>-1, 'msg' =>'顶级分类最多添加3个']);
                }
            }else{
                $mapd = array(
                    'instit_id'=>session('instit_id'),
                    'pid'=>$pids,
                );
                $count1 =   Db::name('wechat_menu')->where($mapd)->count();
                if($count1>=5){
                    return json(['code'=>-1, 'msg' =>'子菜单最多添加5个']);
                }
            }


            $param['instit_id'] = session('instit_id');
            $flag = $wechat->insertWechatMenu($param);


//            $this->pub_menu();


            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }

        $mv = array(
                'instit_id' => session('instit_id'),
                'pid'=>0
        );

        $list= Db::name('wechat_menu')->where($mv)->select();
        $this->assign('list',$list);
        $this->assign('pid',$pid);

        return $this->fetch();
    }

public function menu_edit()
    {

        if(request()->isAjax()){
            $wechat = new WechatModel();
            $param = input('post.');
            $pids = $param['pid'];
            $param['instit_id'] = session('instit_id');
            $flag = $wechat->updateWechatMenu($param);


//            $this->pub_menu();


            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }

        $mv = array(
                'instit_id' => session('instit_id'),
                'pid'=>0
        );
        $id = input('param.id');
        $list= Db::name('wechat_menu')->where($mv)->select();


        $wechat = Db::name('wechat_menu')->where('id',$id)->find();
        $this->assign('list',$list);
        $this->assign('wechat',$wechat);

        return $this->fetch();
    }






    public function menu_del()
    {

//        $user = new UserModel();
//        $res = $user->UserCanOperation($admin_id);  //此用户是否允许添加角色
//        if($res==0){
//            return ['code' => -1, 'data' => '', 'msg' => '无权操作'];
//        }
        $id = input('param.id');
        $role = new WechatModel();
        $flag = $role->menu_del($id);
        return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
    }

    public function repay_del()
    {

//        $user = new UserModel();
//        $res = $user->UserCanOperation($admin_id);  //此用户是否允许添加角色
//        if($res==0){
//            return ['code' => -1, 'data' => '', 'msg' => '无权操作'];
//        }
        $id = input('param.id');
        $role = new WechatModel();
        $flag = $role->repay_del($id);
        return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
    }



    public function repay_index(){
        $cate = new WechatModel();
        $list = $cate->getAllRepay();
        $this->assign('list',$list);
        return $this->fetch();
    }




    public function repay_add()
    {
        if(request()->isAjax()){

            $wechat = new WechatModel();
            $param = input('post.');
            $param['instit_id'] = session('instit_id');
            $flag = $wechat->insertRepay($param);
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }

        return $this->fetch();
    }



    public function repay_edit()
    {
        if(request()->isAjax()){
            $wechat = new WechatModel();
            $param = input('post.');
            $flag = $wechat->editRepay($param);
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }

        $id = input('param.id');
        $repay = Db::name('wechat_repay')->where('id',$id)->find();
        $this->assign('repay',$repay);
        return $this->fetch();
    }


    /*
     * 生成微信菜单
     */
    public function pub_menu(){

//        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxe32eb79836b2072c&secret=600a0cff55222116495320c265b72f05';
//        $result = file_get_contents($url);
//        print_R($result);

        $menu = array();
        $menu['button'][] = array(
            'name'=>'测试',
            'type'=>'view',
            'url'=>'http://www.shuren.com'
        );
        $menu['button'][] = array(
            'name'=>'测试',
            'sub_button'=>array(
                array(
                    "type"=> "scancode_waitmsg",
                    "name"=> "系统拍照发图",
                    "key"=> "rselfmenu_1_0",
                    "sub_button"=> array()
                )
            )
        );



        $instit_id = session('instit_id');
        //$instit_id = 113;
        //获取菜单
        $wechat = Db::name('wechat')->where('instit_id',$instit_id)->find();

        //获取父级菜单
        $p_menus =  Db::name('wechat_menu')->where(array('instit_id'=>$instit_id,'pid'=>0))->order('id ASC')->select();
        $p_menus = convert_arr_key($p_menus,'id');
        $post_str = $this->convert_menu($p_menus);
        $options = [
            'token'=> $wechat['token'],
            'encodingaeskey'=> $wechat['encodingaeskey'],
            'appid'=> $wechat['appid'],
            'appsecret'=> $wechat['appsecret']
        ];

//        print_R($options);
//        print_R($post_str);

        $this->weObj = new \com\Wechat($options);
        $result =  $this->weObj->createMenu($post_str);




        return json($result);



//
//        // http post请求
//        if(!count($p_menus) > 0){
//            $this->error('没有菜单可发布',U('Wechat/menu'));
//            exit;
//        }
//
//
//        $access_token = $this->get_access_token($wechat['appid'],$wechat['appsecret']);
//
//
//
////        if(!$access_token){
////            $this->error('获取access_token失败',U('Wechat/menu'));//  /index.php/Admin/Wechat/menu
////
////            exit;
////        }
//        $url ="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
////        exit($post_str);
//        $return = $this->httpRequest($url,'POST',$post_str);
//        $return = json_decode($return,1);
//
//
//        print_R($return);

//        if($return['errcode'] == 0){
//            $this->success('菜单已成功生成',U('Wechat/menu'));
//        }else{
//            echo "错误代码;".$return['errcode'];
//            exit;
//        }
    }



    //菜单转换
    private function convert_menu($p_menus){
        $key_map = array(
            'scancode_waitmsg'=>'rselfmenu_0_0',
            'scancode_push'=>'rselfmenu_0_1',
            'pic_sysphoto'=>'rselfmenu_1_0',
            'pic_photo_or_album'=>'rselfmenu_1_1',
            'pic_weixin'=>'rselfmenu_1_2',
            'location_select'=>'rselfmenu_2_0',
        );
        $new_arr = array();
        $count = 0;
        foreach($p_menus as $k => $v){
            $new_arr[$count]['name'] = $v['name'];

            $instit_id = session('instit_id');
            //获取子菜单
            $c_menus = Db::name('wechat_menu')->where(array('instit_id'=>$instit_id,'pid'=>$k))->select();

            if($c_menus){
                foreach($c_menus as $kk=>$vv){
                    $add = array();
                    $add['name'] = $vv['name'];
                    $add['type'] = $vv['type'];
                    // click类型
                    if($add['type'] == 'click'){
                        $add['key'] = $vv['value'];
                    }elseif($add['type'] == 'view'){
                        $add['url'] = $vv['value'];
                    }else{
                        //$add['key'] = $key_map[$add['type']];
                        $add['key'] = $vv['value'];
                    }
                    $add['sub_button'] = array();
                    if($add['name']){
                        $new_arr[$count]['sub_button'][] = $add;
                    }
                }
            }else{
                $new_arr[$count]['type'] = $v['type'];
                // click类型
                if($new_arr[$count]['type'] == 'click'){
                    $new_arr[$count]['key'] = $v['value'];
                }elseif($new_arr[$count]['type'] == 'view'){
                    //跳转URL类型
                    $new_arr[$count]['url'] = $v['value'];
                }else{
                    //其他事件类型
                    //$new_arr[$count]['key'] = $key_map[$v['type']];
                    $new_arr[$count]['key'] = $v['value'];  //2016年9月29日01:40:13
                }
            }
            $count++;
        }
        // return json_encode(array('button'=>$new_arr));
        return json_encode(array('button'=>$new_arr),JSON_UNESCAPED_UNICODE);
    }

    public function get_access_token(){

        $instit_id = session('instit_id');
        $wechat =  Db::name('wechat')->where('instit_id',$instit_id)->find();


        print_R($wechat);

        $expire_time = $wechat['web_expires'];
        if($expire_time > time()){
            return $wechat['web_access_token'];
        }
        echo $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$wechat['appid']."&secret=".$wechat['appsecret'];
        $return = $this->httpRequest($url,'GET');
        $return = json_decode($return,1);

        $web_expires = time() + 7000; // 提前200秒过期

      //  M('wx_user')->where(array('id'=>$wechat['id']))->save(array('web_access_token'=>$return['access_token'],'web_expires'=>$web_expires));

        $map3 = array(
            'web_access_token' => $return['access_token'],
            'web_expires'=>$web_expires
        );



//        Db::name('wechat')->wehre('id',$wechat['id'])->update($map3);

        Db::name('wechat')->where('id',$wechat['id'])->update($map3);


        return $return['access_token'];
    }


    function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false) {
        $method = strtoupper($method);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;


                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if($ssl){
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
        $response = curl_exec($ci);
        $requestinfo = curl_getinfo($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo "=====info===== \r\n";
            print_r($requestinfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);
        return $response;
        //return array($http_code, $response,$requestinfo);
    }



}